"""
@author: wtf
@file: config.py
@time: 2024/5/8 16:06
"""
from datetime import datetime
from flask import Flask, session, g
import config
from exts import db, mail
from models import UserModel
from blueprints.qa import bp as qa_bp
from blueprints.auth import bp as auth_bp
from flask_migrate import Migrate
from MyFilter import datatime_format

app = Flask(__name__)

# 绑定配置文件
app.config.from_object(config)
# 添加命令
migrate = Migrate(app, db)

# 配置
db.init_app(app)
mail.init_app(app)

# 注册blueprint
app.register_blueprint(qa_bp)
app.register_blueprint(auth_bp)


# 两个钩子函数
# before_request/ before_first_request /after_request
@app.before_request
def my_before_request():
    user_id = session.get("user_id")
    print("session中的user_id:" + str(user_id))
    if user_id:
        user = UserModel.query.get(user_id)
        setattr(g, "user", user)  # g为 存放 全局对象变量global
    else:
        setattr(g, "user", None)


# 存放全局变量
@app.context_processor
def my_context_professor():
    return {"user": g.user}


# 添加到模版过滤器
app.add_template_filter(datatime_format, "my_format")  # 函数+过滤器名


@app.template_filter("add_msg")
def add_msg(msg):
    return "用户:" + msg


if __name__ == '__main__':
    app.run()
